<template>
	<view class="avatar-container">
		<image :src="avatarUrl || defaultAvatar" class="avatar-image" @click="chooseImage" />
		<view class="upload-text" v-if="showUploadText">
			点击上传头像
		</view>
	</view>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue';

const props = defineProps({
	// 默认头像
	defaultAvatar: {
		type: String,
		default: '/static/default-avatar.png'
	},
	// 当前头像URL
	currentAvatar: {
		type: String,
		default: ''
	},
	// 是否显示上传文字提示
	showUploadText: {
		type: Boolean,
		default: true
	}
});

const emit = defineEmits(['update:currentAvatar', 'uploadSuccess', 'uploadError']);

const avatarUrl = ref(props.currentAvatar);

// 选择图片
const chooseImage = async () => {
	try {
		const res = await uni.chooseImage({
			count: 1, // 只选择一张图片
			sizeType: ['compressed'], // 压缩图片
			sourceType: ['album', 'camera'] // 可以从相册选择或使用相机
		});

		if (res.tempFilePaths && res.tempFilePaths[0]) {
			// 显示上传加载中
			uni.showLoading({
				title: '上传中...'
			});

			// 上传图片
			await uploadImage(res.tempFilePaths[0]);

		}
	} catch (err) {
		console.error('选择图片失败:', err);
		uni.showToast({
			title: '选择图片失败',
			icon: 'none'
		});
	}
};

// 上传图片
const uploadImage = async (tempFilePath) => {
	try {
		// 使用 uniCloud 上传文件
		const result = await uniCloud.uploadFile({
			filePath: tempFilePath,
			cloudPath: `avatar/${Date.now()}-${Math.random().toString(36).slice(-6)}.jpg`,
			onUploadProgress: (progressEvent) => {
				const percentCompleted = Math.round(
					(progressEvent.loaded * 100) / progressEvent.total
				);
				console.log('上传进度：', percentCompleted);
			}
		});

		// 更新头像URL
		avatarUrl.value = result.fileID;

		// 触发更新事件
		emit('update:currentAvatar', avatarUrl.value);
		emit('uploadSuccess', result);

		uni.showToast({
			title: '上传成功',
			icon: 'success'
		});
	} catch (err) {
		console.error('上传失败:', err);
		emit('uploadError', err);
		uni.showToast({
			title: '上传失败',
			icon: 'none'
		});
	} finally {
		uni.hideLoading();
	}
};
</script>

<style lang="scss" scoped>
.avatar-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	margin: 0 auto;

	.avatar-image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #f5f5f5;
		object-fit: cover;
	}

	.upload-text {
		position: absolute;
		bottom: -40rpx;
		left: 50%;
		transform: translateX(-50%);
		font-size: 24rpx;
		color: #666;
		white-space: nowrap;
	}
}
</style>